package com.eliteams.quick4j.web.app.wechat;

import com.alibaba.fastjson.JSONObject;
import com.eliteams.quick4j.core.util.HttpsGetUtil;
import com.eliteams.quick4j.core.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * @FileName Oauth2Servlet.java
 * @Description 微信网页授权
 * @Version 1.0
 * @Author liugy.
 * @Email 958130364@qq.com
 * @History <br>
 * <li>Author: liugy</li>
 * <li>Date: 2017-02-15</li>
 * <li>Version: 1.0</li>
 * <li>Content: create</li>
 */
public class Oauth2Servlet {
	/** 普通日志 */
	private static final Logger	logger			= LoggerFactory.getLogger(Oauth2Servlet.class);
												
	/** 用户同意授权，获取code */
	private static String		get_code_url	= "https://open.weixin.qq.com/connect/oauth2/authorize?"
													+ "appid=APPID" + "&redirect_uri=REDIRECT_URI"
													+ "&response_type=code" + "&scope=SCOPE"
													+ "&state=STATE" + "#wechat_redirect ";

	/** 通过code换取网页授权access_token */
	private static String get_access_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?"
			+ "appid=APPID" + "&secret=SECRET&"
			+ "code=CODE&grant_type=authorization_code";


	/**
	 *  第一步 用户同意授权，获取code
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	public static void toWeChat(HttpServletRequest request,
								HttpServletResponse response) throws IOException {
		String STATE = request.getParameter("state");
		if (StringUtil.isNotEmpty(STATE)) {
			get_code_url = get_code_url.replace("STATE", STATE);
		}
		String returnUrl = request.getRequestURL().substring(0,
			request.getRequestURL().length() - request.getRequestURI().length())
							+ "/app/weixinLogin.htm";
		get_code_url = get_code_url.replace("APPID", "wechatAppId");
		get_code_url = get_code_url.replace("REDIRECT_URI", URLEncoder.encode(returnUrl, "UTF-8"));
		response.sendRedirect(get_code_url);
	}

	/**
	 * 第二步：通过code换取网页授权access_token
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
     */
	public static JSONObject getOpenIdByCode(HttpServletRequest request,
											 HttpServletResponse response)	throws ServletException,
			IOException {

		// 将请求、响应的编码均设置为UTF-8（防止中文乱码）  
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		String code = request.getParameter("code");

		get_access_token_url = get_access_token_url.replace("APPID","wechatAppId");
		get_access_token_url = get_access_token_url.replace("SECRET","wechatAppSecret");
		get_access_token_url = get_access_token_url.replace("CODE", code);

		logger.info("CODE", code);

		String accessTokenStr = HttpsGetUtil.doHttpsGetJson(get_access_token_url);
		
		JSONObject accessTokenJson = JSONObject.parseObject(accessTokenStr);

		String access_token = (String) accessTokenJson.get("access_token");
		String openid = (String) accessTokenJson.get("openid");
		request.getSession().setAttribute("access_token", access_token);
		request.getSession().setAttribute("openid", openid);

		logger.info("微信token{}", accessTokenJson);
		return accessTokenJson;
	}
}
